/**
 * Created by hcadmin on 16/11/7.
 */
$(function(){
    var _name = 0;
    var _time = 0;
    var _modal="";
    var _start="";
    var _stop ="";
    var _list ="";

    var index = "0"; //用于判断  筛选的返回  和 报表的返回  0-报表页  1-筛选页

    //进入页面展示的数据  为空
    $(".table_div").append("<div class='table_tr blank_text'><div class='hint_div' style='line-height: 12.5vh;color: #646464;width: 100%;text-align: center'>请进行筛选</div></div>");
    //点击筛选
    $(".right_div").on('click',function(){
        $(".start").val("开始时间");
        $(".stop").val("结束时间");
        $(".export_img").hide();
        $(".table_div").hide();
        $(".model_body").hide();

        index = "1";
        //模板展示
        initLogModelList(group_id,"-1","3");
    });

    //--选择时间
    var currYear = (new Date()).getFullYear();
    var opt = {};
    opt.date = { preset: 'date' };
    opt.datetime = { preset: 'datetime' };
    opt.time = { preset: 'time' };
    opt.default = {
        theme: 'sense-ui', //皮肤样式
        display: 'modal', //显示方式
        mode: 'scroller', //日期选择模式
        lang: 'zh',
        startYear: currYear - 10, //开始年份
        endYear: currYear + 10 //结束年份
    };
    var optDateTime = $.extend(opt['datetime'], opt['default']);
    $(".start").mobiscroll(optDateTime).date(optDateTime);
    $(".stop").mobiscroll(optDateTime).date(optDateTime);

    //--选择模板
    $(document).on('click','.model_body',function(){
        $(".model_body").attr("data-choiced","0")
                        .css("backgroundColor","#EDF0F0");
        $(this).attr("data-choiced","1");
        $(this).css("backgroundColor","#a488e4");
    });

    //--点击取消
    $(".cancel").on('click',function(){
        $(".table_div").show();
        $(".export_img").show();
        $(".choice_div_content").hide();
        $(".model_body").remove();
        $(".start").val("开始时间");
        $(".stop").val("结束时间");

        index = "0";
    });
    //--点击 确定
    $(".sure").on('click',function(){
        index = "0";
        //先移除之前有的表格
        $(".title_div_row").remove();
        //获取模板id
        var model_id;
        $(".model_body").each(function(index){
            if($(this).attr("data-choiced")=="1"){
                _modal = model_id = $(this).attr("data-id");
                $(".export_img").show();
            }
        });

        //获取时间
        var start_time;
        var start_val = $(".start").val();
        var stop_time;
        var stop_val = $(".stop").val();
        initTimestamp(start_val+" 00:00:00");
        _start = start_time = timestamp;
        initTimestamp(stop_val+" 23:59:59");
        _stop = stop_time = timestamp;


        if(start_val=="开始时间"){
            $(".blank_prompt_box").html("请选择开始时间").show().fadeOut(2000);
        }else if(stop_val=="结束时间"){
            $(".blank_prompt_box").html("请选择结束时间").show().fadeOut(2000);
        }else if(model_id==undefined){
            $(".blank_prompt_box").html("请选择模板").show().fadeOut(2000);
        }else{
            initData(model_id,start_time,stop_time,"0","0");
        }
    });


    function setTitleBlock(title_name,row,sequence){
        var titleBlock = "";
        if (sequence == 0){
            //不用排序
            titleBlock = "<div class='title_div_row_block content_div_row_block_text' row='" + row + "'>" + title_name + "</div>";
        }else {
            titleBlock = "<div class='title_div_row_block' row='" + row + "'><div class='title_div_row_block_text'>"+ title_name +"</div><img src='../logImg/logreportsort0.png' class='sort sort_name'><div style='clear: both;'></div></div>";
        }
        return titleBlock;
    }

    function setContentBlock(content,row){
        var contentBlock =
            "<div class='title_div_row_block content_div_row_block_text' row='" + row + "'>" + content + "</div>";
        return contentBlock;
    }

    function initData(model_id,start_time,stop_time,name,time){
        var url = apiurl+"/dailyrecords/report/"+model_id+"";
        $.ajax({
            beforeSend:function(){
                $(".loading").show();
                $(".table_div").hide();
                $(".choice_div_content").hide();
            },
            url:url,
            type:"GET",
            data:{
                user_id:user_id,
                group_id:group_id,
                begin:start_time,
                end:stop_time,
                name_sort:name,
                time_sort:time
            },
            success:function(d){
                var call_back = JSON.parse(d);
                var code = call_back.code;
                var data = call_back.data;
                var list = data.list;
                _list = list;
                if(code == "0"){
                    if(list.length > 0){
                        //标题栏设置
                        var totalWidth = "";
                        var reporter = setTitleBlock("填报人",0,1);
                        var reportTime = setTitleBlock("填报时间",0,1);
                        //取第一条数据做基准
                        var fieldValues0     = list[0].fieldValues;
                        //默认的填报人,填报时间
                        $(".table_div").append("<div class='title_div_row title_div_row_background'>" + reporter + reportTime + "</div>");
                        for(var j = 0; j < fieldValues0.length; j++){
                            var title = fieldValues0[j].dailyrecord_temp_field_title;
                            $(".title_div_row_background").append(setTitleBlock(title,0,0));
                            if (j == fieldValues0.length - 1){
                                $(".title_div_row_background").append("<div style='clear: both'></div>");
                            }
                        }
                        totalWidth = (fieldValues0.length + 2) * 30 + "vw";




                        for (var i = 0; i < list.length; i ++){
                            //基础数据
                            var create_timestamp = list[i].create_timestamp;                //日志创建时间
                            initDate(new Date(create_timestamp));
                            var time_create      = day_min;
                            var user_id          = list[i].user_id;                         //日志创建人
                            var user_name        = list[i].user_name;
                            var fieldValues      = list[i].fieldValues;                     //日志模板详情



                            var row = i + 1;

                            var user_html = setContentBlock(user_name,i + 1);
                            var time_html = setContentBlock(time_create,i + 1);


                            var td_html = "";

                            for(var v = 0; v < fieldValues.length; v++){
                                var type = fieldValues[v].daiyrecord_temp_field_type;
                                var val  = fieldValues[v].default_value;
                                if(type=="3"){
                                    initDate(new Date(Math.round(val)));
                                    val = year_whole;
                                }
                                if(type=="4"){
                                    initDate(new Date(Math.round(val)));
                                    val = year_mon_day;
                                }
                                td_html += setContentBlock(val,i + 1);
                            }
                            //user_html = "<div class='td'>"+user_name+"</div>";
                            //time_html = "<div class='td'>"+time_create+"</div>";
                            $(".table_div").append("<div class='title_div_row' row='"+ row +"'>" + user_html + time_html + td_html + "<div style='clear: both'></div></div>");

                        }

                        //$(".table_div").append("<div class='table_tr table_title'><div class='th'>填报人<img src='../logImg/logreportsort0.png' class='sort sort_name'></div><div class='th'>填报时间<img src='../logImg/logreportsort0.png' class='sort sort_time'></div></div>");
                        //for(var i=0;i<list.length;i++){
                        //    var tr_html="";
                        //    var user_html="";
                        //    var time_html="";
                        //    var td_html="";
                        //    var create_timestamp = list[i].create_timestamp;                //日志创建时间
                        //    initDate(new Date(create_timestamp));
                        //    var time_create      = day_min;
                        //    var user_id          = list[i].user_id;                         //日志创建人
                        //    var user_name        = list[i].user_name;
                        //    var fieldValues      = list[i].fieldValues;                     //日志模板详情
                        //    var fieldValues0     = list[0].fieldValues;
                        //    //先将title获取并append上去
                        //    if(i==0){
                        //        for(var j=0;j<fieldValues0.length;j++){
                        //            var title = fieldValues0[j].dailyrecord_temp_field_title;
                        //            $(".table_title").append("<div class='th'>"+title+"</div>");
                        //
                        //            if (j == fieldValues0.length - 1){
                        //                $(".table_title").append("<div style='clear: both'></div>");
                        //            }
                        //        }
                        //        totalWidth = (fieldValues0.length + 2) * 30 + "vw";vw
                        //    }
                        //    for(var v=0;v<fieldValues.length;v++){
                        //        var type = fieldValues[v].daiyrecord_temp_field_type;
                        //        var val  = fieldValues[v].default_value;
                        //        if(type=="3"){
                        //            initDate(new Date(Math.round(val)));
                        //            val = year_whole;
                        //        }
                        //        if(type=="4"){
                        //            initDate(new Date(Math.round(val)));
                        //            val = year_mon_day;
                        //        }
                        //        td_html += "<div class='td'>"+val+"</div>";
                        //    }
                        //    user_html = "<div class='td'>"+user_name+"</div>";
                        //    time_html = "<div class='td'>"+time_create+"</div>";
                        //
                        //
                        //    tr_html = "<div class='table_tr'>"+user_html+""+time_html+""+td_html+"<div style='clear: both'></div></div>";
                        //    $(".table_div").append(tr_html);
                        //    //$(".table_tr").width((fieldValues0.length + 2) * 30 + "vw");
                        //
                        //
                        //}
                        $(".title_div_row").width(totalWidth);
                        $(".blank_text").hide();

                        //高度设置

                        var poller = window.setInterval(function(){
                            var count = document.getElementsByClassName("title_div_row").length;
                            if(count == list.length + 1){ //DOM is much more efficient
                                window.clearInterval(poller);
                                $(".title_div_row").each(function(index){

                                    var height = 0;
                                    $(".title_div_row_block[row='" + index + "']").each(function(){
                                        var current_height = $(this).outerHeight();
                                        if (current_height > height){
                                            height = current_height;
                                        }
                                    });
                                    $(".title_div_row_block[row='" + index + "']").each(function(){
                                        $(this).outerHeight(height);
                                    });
                                });
                                //$(detected).remove(); //Remove marker
                                //for(var i=0; i<site.pageData.length; i++){
                                //    var loader = site.pageData[i];
                                //    $(loader.loadInTo).load(loader.url + ' ' + loader.urlSection);
                                //}
                            }
                        }, 100);

                        //setTimeout(function(){
                        //    $(".title_div_row").each(function(index){
                        //
                        //        var height = 0;
                        //        $(".title_div_row_block[row='" + index + "']").each(function(){
                        //            var current_height = $(this).outerHeight();
                        //            if (current_height > height){
                        //                height = current_height;
                        //            }
                        //        });
                        //        $(".title_div_row_block[row='" + index + "']").each(function(){
                        //            $(this).outerHeight(height);
                        //        });
                        //    });
                        //},200);




                    }else{
                        $(".blank_text").show();
                        $(".hint_div").html("暂无报表");
                        //$(".table_tr")
                        //$(".table_div").append("<div class='table_tr blank_text'><div class='td' style='text-align: center'>暂无报表</div></div>");
                    }
                    $(".loading").hide();
                    $(".table_div").show();
                    $(".choice_div_content").hide();
                }
            }
        })
    }

    //点击名字排序
    $(document).on('click','.sort_name',function(){
        $(".title_div_row").remove();
        if(_name==0){
            initData(_modal,_start,_stop,"1","0");
            _name=1
        }else{
            initData(_modal,_start,_stop,"2","0");
            _name=0;
        }
    });
    //点击 时间 筛选
    $(document).on('click','.sort_time',function(){
        $(".title_div_row").remove();
        if(_time==0){
            initData(_modal,_start,_stop,"0","1");
            _time=1
        }else{
            initData(_modal,_start,_stop,"0","2");
            _time=0;
        }
    });
    //点击导出按钮
    var downloadLogReport;
    downloadLogReport                      = document.createElement('iframe');
    downloadLogReport.style.display        = 'none';
    document.documentElement.appendChild(downloadLogReport);
    $(".export_img").on('click',function(){
        if(_modal!=""&&_start!=""&&_stop!=""&&_list.length>0){
            var dl_url = ""+apiurl+"/dailyrecords/report/"+_modal+"/export?group_id="+localStorage.group_id+"&begin="+_start+"&end="+_stop+"&export_user_id="+localStorage.user_id+"&token="+localStorage.token+"";

            downloadLogReport.src          = "downloadLogReport_url?url="+dl_url+"";
        }
    });

    //退出报表界面时 传递 参数 src 用于判断 横竖屏

    //退出报表界面
    $(".left_div").on('click',function(){

        if(index == "0") {
            var quitLogReportForm;
            quitLogReportForm = document.createElement('iframe');
            quitLogReportForm.style.display = 'none';
            quitLogReportForm.id = 'quitReport';
            document.documentElement.appendChild(quitLogReportForm);
            quitLogReportForm.src = "/quitLogReportForm_quitCrossScreen";
            //$("#quitReport").remove();
            window.history.back(-1);
        }else{
            $(".table_div").show();
            $(".export_img").show();
            $(".choice_div_content").hide();
            $(".model_body").remove();
            $(".start").val("开始时间");
            $(".stop").val("结束时间");

            index = "0";
        }
    })
});
